package flc.ast.fragment;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.Drawable;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.AttachPopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnSelectListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.ImgDetailActivity;
import flc.ast.activity.SelPictureActivity;
import flc.ast.activity.SelAudioActivity;
import flc.ast.activity.SelPicActivity;
import flc.ast.activity.SelVideoActivity;
import flc.ast.activity.VideoDetailActivity;
import flc.ast.activity.VideoRecordActivity;
import flc.ast.adapter.CreationRecordAdapter;
import flc.ast.adapter.HomeVideoAdapter;
import flc.ast.bean.MyFileBean;
import flc.ast.databinding.FragmentHomeBinding;
import flc.ast.utils.Content;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.audio.AudioPlayerImpl;
import stark.common.basic.media.audio.IAudioPlayer;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.StatusBarUtils;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseNoModelFragment<FragmentHomeBinding> {

    private List<MyFileBean> listShow = new ArrayList<>();
    private List<MyFileBean> listVideo = new ArrayList<>();
    private AttachPopupView attachPopupView;
    private Dialog myRenameDialog, myDeleteDialog;
    private EditText editText;
    private int selPosition;
    private HomeVideoAdapter videoAdapter;
    private CreationRecordAdapter recordAdapter;
    private int type = 0;
    protected IAudioPlayer mAudioPlayer;


    @Override
    protected int onCreate() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        StatusBarUtils.setSystemStatusTextColor(true, getActivity());

        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mAudioPlayer = new AudioPlayerImpl();


        mDataBinding.rvVideoRecord.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        videoAdapter = new HomeVideoAdapter();
        mDataBinding.rvVideoRecord.setAdapter(videoAdapter);

        mDataBinding.rvRecordList.setLayoutManager(new GridLayoutManager(mContext, 3));
        recordAdapter = new CreationRecordAdapter();
        mDataBinding.rvRecordList.setAdapter(recordAdapter);
        recordAdapter.addChildClickViewIds(R.id.ivCreationRecordItemEdit);
        recordAdapter.addChildClickViewIds(R.id.rlCreationRecordItem);
        recordAdapter.setOnItemChildClickListener(this);

        mDataBinding.llVideoEdit.setOnClickListener(this);
        mDataBinding.rlPicEdit.setOnClickListener(this);
        mDataBinding.rlAudioEdit.setOnClickListener(this);
        mDataBinding.tvPosterPuzzle.setOnClickListener(this);
        mDataBinding.tvPosterMake.setOnClickListener(this);
        mDataBinding.tvMusicAlbum.setOnClickListener(this);
        mDataBinding.tvPictureSpecial.setOnClickListener(this);
        mDataBinding.tvAudioExtraction.setOnClickListener(this);
        mDataBinding.ivVideoRecord.setOnClickListener(this);
        mDataBinding.tvImageRecord.setOnClickListener(this);
        mDataBinding.tvVideoRecord.setOnClickListener(this);
        mDataBinding.tvAudioRecord.setOnClickListener(this);
        //重命名弹框
        renameDialog();
        //删除弹框
        deleteDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.llVideoEdit://视频编辑
                SelVideoActivity.type = 0;
                startActivity(SelVideoActivity.class);
                break;
            case R.id.ivVideoRecord://视频创作记录
                startActivity(VideoRecordActivity.class);
                break;
            case R.id.rlPicEdit://图片编辑
                SelPicActivity.type = 0;
                startActivity(SelPicActivity.class);
                break;
            case R.id.rlAudioEdit://音频编辑
                startActivity(SelAudioActivity.class);
                break;
            case R.id.tvPosterPuzzle://海报拼图
                SelPictureActivity.type = 0;
                startActivity(SelPictureActivity.class);
                break;
            case R.id.tvPosterMake://海报制作
                SelPictureActivity.type = 1;
                startActivity(SelPictureActivity.class);
                break;
            case R.id.tvMusicAlbum://音乐相册
                SelPictureActivity.type = 2;
                startActivity(SelPictureActivity.class);
                break;
            case R.id.tvPictureSpecial://图片特效
                SelPicActivity.type = 1;
                startActivity(SelPicActivity.class);
                break;
            case R.id.tvAudioExtraction://音频提取
                SelVideoActivity.type = 1;
                startActivity(SelVideoActivity.class);
                break;
            case R.id.tvImageRecord://图片
                clearSelection();
                type = 0;
                mDataBinding.tvImageRecord.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvImageRecord.setBackgroundColor(Color.parseColor("#34E0A1"));
                getImageData();
                break;
            case R.id.tvVideoRecord://视频
                clearSelection();
                type = 1;
                mDataBinding.tvVideoRecord.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvVideoRecord.setBackgroundColor(Color.parseColor("#34E0A1"));
                getVideoData();
                break;
            case R.id.tvAudioRecord://音频
                clearSelection();
                type = 2;
                mDataBinding.tvAudioRecord.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvAudioRecord.setBackgroundColor(Color.parseColor("#34E0A1"));
                getAudioData();
                break;
            //重命名
            case R.id.ivDialogRenameConfirm:
                String name = editText.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(getText(R.string.please_input_video_name));
                    return;
                }
                FileUtils.rename(recordAdapter.getItem(selPosition).getUrl(), name + "." + FileUtils.getFileExtension(recordAdapter.getItem(selPosition).getUrl()));
                myRenameDialog.dismiss();
                editText.setText("");
                if (type == 0) {
                    getImageData();
                } else if (type == 1) {
                    getVideoData();
                } else if (type == 2) {
                    getAudioData();
                }
                break;
            case R.id.ivDialogRenameCancel:
                editText.setText("");
                myRenameDialog.dismiss();
                break;
            //删除
            case R.id.ivDialogDeleteConfirm:
                FileUtils.delete(recordAdapter.getItem(selPosition).getUrl());
                myDeleteDialog.dismiss();
                if (type == 0) {
                    getImageData();
                } else if (type == 1) {
                    getVideoData();
                    getHomeVideo();
                } else if (type == 2) {
                    getAudioData();
                }
                break;
            case R.id.ivDialogDeleteCancel:
                myDeleteDialog.dismiss();
                break;
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        selPosition = position;
        switch (view.getId()) {
            case R.id.ivCreationRecordItemEdit:
                attachPopupView = new XPopup.Builder(mContext)
                        .hasShadowBg(false)
//                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
//                        .isDarkTheme(true)
//                        .popupAnimation(PopupAnimation.NoAnimation) //NoAnimation表示禁用动画
//                        .isCenterHorizontal(true) //是否与目标水平居中对齐
//                        .offsetY(-60)
//                        .offsetX(80)
                        .popupPosition(PopupPosition.Left) //手动指定弹窗的位置
                        .atView(view)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                        .asAttachList(new String[]{getString(R.string.delete), getString(R.string.share), getString(R.string.rename)},
                                new int[]{R.drawable.ashanchu, R.drawable.afenx, R.drawable.achongmm},
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        switch (position) {
                                            case 0:
                                                myDeleteDialog.show();
                                                break;
                                            case 1:
                                                IntentUtil.shareVideo(mContext, recordAdapter.getItem(selPosition).getUrl());
                                                break;
                                            case 2:
                                                myRenameDialog.show();
                                                break;
                                        }
                                    }
                                }, 0, 0);
                ;
//                }
                attachPopupView.show();
                break;
            case R.id.rlCreationRecordItem:
                if (type == 0) {
                    ImgDetailActivity.imgPath = listShow.get(position).getUrl();
                    startActivity(ImgDetailActivity.class);
                } else if (type == 1) {
                    VideoDetailActivity.videoPath = listShow.get(position).getUrl();
                    startActivity(VideoDetailActivity.class);
                } else if (type == 2) {
                    MyFileBean bean = recordAdapter.getItem(position);
                    if (bean.isSelect()) {
                        bean.setSelect(false);
                        mAudioPlayer.pause();
                    } else {
                        for (MyFileBean validDatum : recordAdapter.getValidData()) {
                            validDatum.setSelect(false);
                        }
                        bean.setSelect(true);
                        mAudioPlayer.play(bean.getUrl());
                    }
                    recordAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onResume() {
        super.onResume();
        getHomeVideo();
        if (type == 0) {
            getImageData();
        } else if (type == 1) {
            getVideoData();
        } else if (type == 2) {
            getAudioData();
        }
    }

    private void getHomeVideo() {
        listVideo.clear();
        String path = PathUtils.getFilesPathExternalFirst() + Content.myVideo;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                listVideo.add(new MyFileBean(file.getPath(), false));
            }
        }
        if (listVideo.size() > 0) {
            if (listVideo.size() > 3) {
                listVideo = listVideo.subList(0, 3);
            }
            videoAdapter.setList(listVideo);
            mDataBinding.rvVideoRecord.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.rvVideoRecord.setVisibility(View.GONE);
        }
    }

    //获取图片数据
    private void getImageData() {
        listShow.clear();
        String path = PathUtils.getFilesPathExternalFirst() + Content.myImage;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                listShow.add(new MyFileBean(file.getPath(), false));
            }
        }
        if (listShow.size() > 0) {
            recordAdapter.setType(type);
            recordAdapter.setList(listShow);
            mDataBinding.rvRecordList.setVisibility(View.VISIBLE);
            mDataBinding.ivRecordNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvRecordList.setVisibility(View.GONE);
            mDataBinding.ivRecordNoData.setVisibility(View.VISIBLE);
        }
    }

    //获取视频数据
    private void getVideoData() {
        listShow.clear();
        String path = PathUtils.getFilesPathExternalFirst() + Content.myMusicAlbum;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                listShow.add(new MyFileBean(file.getPath(), false));
            }
        }
        if (listShow.size() > 0) {
            recordAdapter.setType(type);
            recordAdapter.setList(listShow);
            mDataBinding.rvRecordList.setVisibility(View.VISIBLE);
            mDataBinding.ivRecordNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvRecordList.setVisibility(View.GONE);
            mDataBinding.ivRecordNoData.setVisibility(View.VISIBLE);
        }
    }

    //获取音频数据
    private void getAudioData() {
        listShow.clear();
        String path = PathUtils.getFilesPathExternalFirst() + Content.myAudio;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                listShow.add(new MyFileBean(file.getPath(), false));
            }
        }
        if (listShow.size() > 0) {
            recordAdapter.setType(type);
            recordAdapter.setList(listShow);
            mDataBinding.rvRecordList.setVisibility(View.VISIBLE);
            mDataBinding.ivRecordNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvRecordList.setVisibility(View.GONE);
            mDataBinding.ivRecordNoData.setVisibility(View.VISIBLE);
        }
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogRenameCancel);
        ImageView comp = inflate.findViewById(R.id.ivDialogRenameConfirm);
        editText = inflate.findViewById(R.id.etDialogFormatRename);
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(true);
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogDeleteCancel);
        ImageView comp = inflate.findViewById(R.id.ivDialogDeleteConfirm);
        TextView tip = inflate.findViewById(R.id.tvDialogDeleteTip);
        // 设置文本及其颜色
        StringBuffer str = new StringBuffer();
        str.append(getString(R.string.delete_tip1));
        str.append("<font color='#FF3838'>" + getString(R.string.delete_tip2) + "</font>");
        str.append(getString(R.string.delete_tip3));
        // 在文本控件中显示
        tip.setText(Html.fromHtml(str.toString(), getImageGetter(), null));
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    private Html.ImageGetter getImageGetter() {
        return source -> {
            Drawable drawable = getActivity().getDrawable(Integer.parseInt(source));
            drawable.setBounds(0, 0, 60, 60);
            return drawable;
        };
    }

    private void clearSelection() {
        mDataBinding.tvImageRecord.setTextColor(Color.parseColor("#D1D1D1"));
        mDataBinding.tvImageRecord.setBackgroundColor(Color.parseColor("#FFFFFF"));
        mDataBinding.tvVideoRecord.setTextColor(Color.parseColor("#D1D1D1"));
        mDataBinding.tvVideoRecord.setBackgroundColor(Color.parseColor("#FFFFFF"));
        mDataBinding.tvAudioRecord.setTextColor(Color.parseColor("#D1D1D1"));
        mDataBinding.tvAudioRecord.setBackgroundColor(Color.parseColor("#FFFFFF"));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mAudioPlayer != null) {
            mAudioPlayer.stop();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mAudioPlayer != null) {
            mAudioPlayer.pause();
        }
    }

}